<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;

class Payhistory extends Api
{
    protected $noNeedLogin = ['*'];

    public function sendPayhistory()
    {
        $pay_way = input('type/d', 2);
        if ($pay_way != 2) {
            $this->error('支付方式错误');
        }
        $user = User::get($this->auth->id);

        $end_time = $user->shop_end_time != '0000-00-00' ? strtotime($user->shop_end_time) : 0;
        $end_time = $end_time < time() ? 0 : $end_time;
        Db::startTrans();
        try {
            $merchant_renewal_day   = config('site.merchant_renewal_day');   // 商家续费有效期
            $merchant_renewal_stone = config('site.merchant_renewal_stone'); // 商家续费费用(石头)

            $shop_end_time = $end_time > 0 ? date('Y-m-d', $end_time + $merchant_renewal_day * 86400) : date('Y-m-d', time() + $merchant_renewal_day * 86400);
            // 石头支付
            $amount = $merchant_renewal_stone;

            // 获取时候数量
            if ($user->green_stone_amount < $amount) {
                exception('绿石头不足');
            }

            $pay_no = 'X' . date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $data = [
                'user_id'             => $this->auth->id,
                'pay_way'             => $pay_way,
                'amount'              => $pay_way == 1 ? $amount / 100 : $amount,
                'renewal_day'         => $merchant_renewal_day,
                'renewal_expire_date' => $shop_end_time,
                'pay_no'              => $pay_no,
                'createtime'          => time(),
                'updatetime'          => time(),
            ];

            Db::name('user_payhistory')->insert($data);

            Db::name('User')->where('id', $this->auth->id)->update([
                'shop_end_time' => $shop_end_time,
                'is_shop'       => 1,
            ]);

            if ($pay_way == 2) {
                Db::name('user')->where('id', $this->auth->id)->update([
                    'green_stone_amount' => $user->green_stone_amount - $amount,
                ]);

                //同时要记入石头流水
                $data = [
                    'type' => 2,
                    'from_id' => $this->auth->id,
                    'stone_type' => 1,
                    'amount' => $pay_way == 1 ? $amount / 100 : $amount,
                    'consumeinfo' => '商家续期',
                    'createtime'          => time(),
                    'updatetime'          => time(),
                ];

                Db::name('partner_stone_log')->insert($data);

            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $user = User::get($this->auth->id);
        $userInfo = $this->auth->getUserinfo($user);
        $this->success('提交成功', ['userInfo' => $userInfo]);
    }

}
